/**
 * Copyright 2009 Henning Teek, Ingo Renner
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.bricket.plugin.mail.repository.jpa.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.velocity.VelocityEngineUtils;

import com.googlecode.bricket.plugin.mail.domain.Mailserver;
import com.googlecode.bricket.plugin.mail.repository.MailService;
import com.googlecode.bricket.plugin.mail.repository.jpa.MailserverDao;
import com.googlecode.bricket.plugin.user.domain.User;

@Service(value="mailService")
@Transactional
public class MailServiceImpl implements MailService {
	private final static Logger log = LoggerFactory.getLogger(MailServiceImpl.class);

	private static final String DEFAULT_MAILSERVER_NAME = "default";

	@Autowired
	private VelocityEngine velocityEngine;

	@Resource
	private MailserverDao mailserverDao;

	private HashMap<String, JavaMailSenderImpl> mailSenders = new HashMap<String, JavaMailSenderImpl>();

    @Override
	public void init() {
		if (mailserverDao.count().longValue() == 0) {
			Mailserver mailserver = new Mailserver();
			mailserver.setName(DEFAULT_MAILSERVER_NAME);
			mailserver.setHost("localhost");
			mailserver.setPort(25);
			mailserver = saveMailserver(mailserver);
			log.info("auto generated default mailserver created. " + mailserver.getHost() + ":" + mailserver.getPort());
		}
	}

    @Override
	public void deleteMailserver(Mailserver mailserver) {
		mailserverDao.delete(mailserver);
	}

	@Override
	public List<Mailserver> loadAllMailserver() {
		return mailserverDao.readAll();
	}

	@Override
	public Mailserver loadMailserver(Long id) {
		return mailserverDao.readByPrimaryKey(id);
	}

	@Override
	public Mailserver saveMailserver(Mailserver mailserver) {
		return mailserverDao.save(mailserver);
	}

	@Override
	public boolean sendSignupMail(final User user) {
		Map<String, User> model = new HashMap<String, User>();
		model.put("user", user);
		String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "com/googlecode/bricket/plugin/mail/repository/signup.vm", model);
		return sendMail("webmaster@bricket.googlecode.com", user.getEmail(), "Account activation change configs", text);
	}

	@Override
	public boolean sendMail(final String from, final String to, final String subject, final String text) {
		return sendMail(null, from, to, null, null, subject, text, true);
	}

	@Override
	public boolean sendMail(final String mailserver, final String from, final String to, final String cc, final String bcc,
			final String subject, final String text, final boolean html) {
		MimeMessagePreparator preparator = new MimeMessagePreparator() {
			public void prepare(MimeMessage mimeMessage) throws Exception {
	            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
	            message.setFrom(from);
	            message.setTo(to);
	            if (cc != null) {
	            	message.setCc(cc);
	            }
	            if (bcc != null) {
	            	message.setBcc(bcc);
	            }
	            message.setSubject(subject);
	            message.setText(text, html);
			}
		};

		try {
			if (mailserver != null) {
				getMailSender(mailserver).send(preparator);
			} else {
				getDefaultMailSender().send(preparator);
			}
			return true;
		} catch (MailException me) {
			log.error("error sending mail", me);
		}
		return false;
	}

	private JavaMailSenderImpl getMailSender(String name) {
		if (!mailSenders.containsKey(name)) {
			Mailserver mailserver = mailserverDao.findByName(name);

			if (mailserver == null) {
				throw new RuntimeException("mailserver not found");
			}

			JavaMailSenderImpl mailsender = new JavaMailSenderImpl();
			mailsender.setHost(mailserver.getHost());
			if (mailserver.getPort() > 0) {
				mailsender.setPort(mailserver.getPort());
			}
			if (mailserver.getUsername() != null) {
				mailsender.setUsername(mailserver.getUsername());
			}
			if (mailserver.getPassword() != null) {
				mailsender.setUsername(mailserver.getPassword());
			}
			mailSenders.put(mailserver.getName(), mailsender);
		}
		return mailSenders.get(name);
	}

	private JavaMailSenderImpl getDefaultMailSender() {
		return getMailSender(DEFAULT_MAILSERVER_NAME);
	}

	public boolean send(SimpleMailMessage mailMsg) {
		return send(DEFAULT_MAILSERVER_NAME, mailMsg);
	}

	public boolean send(String server, SimpleMailMessage mailMsg) {
		try {
			getMailSender(server == null ? DEFAULT_MAILSERVER_NAME : server).send(mailMsg);
			return true;
		} catch (MailException me) {
			log.error("error sending mail", me);
		}
		return false;
	}
}
